package com.nervenets.web.controller.setting;

import com.nervenets.web.controller.BaseController;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.entity.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api(value = "设置接口v1", description = "设置相关接口")
@RestController
@RequestMapping("/api/v1/setting")
public class SettingController extends BaseController {

    @ApiOperation("系统参数设置")
    @PostMapping("/ruleEdit")
    public ResponseResult ruleEdit(@RequestBody GlobalRuleParams params) {
        final Set<ConstraintViolation<GlobalRuleParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        if (params.resolveUserId() == 0) return errorMessage(MessageCode.code_777);

        globalVariablesService.setGlobalRule(params.toGlobalRule());
        return successMessage();
    }

    @ApiOperation("系统参数获取")
    @PostMapping("/ruleGet")
    public ResponseResult ruleGet() {
        List<GlobalRuleFiled> ruleParams = new ArrayList<GlobalRuleFiled>();
        final Field[] fields = GlobalRuleParams.class.getDeclaredFields();
        for (Field field : fields) {
            final String fieldName = field.getName();
            String description = null;
            if (field.isAnnotationPresent(ApiModelProperty.class)) {
                final ApiModelProperty needValidation = field.getAnnotation(ApiModelProperty.class);
                description = needValidation.value();
            }
            final Class<?> fieldType = field.getType();
            final String fieldTypeName = fieldType.getSimpleName();
            ruleParams.add(new GlobalRuleFiled(fieldName, description, fieldTypeName));
        }
        return successMessage(new GlobalRuleModel(globalVariablesService.getGlobalRule(), ruleParams));
    }
}
